import { CheckSquareOutlined } from '@ant-design/icons'
import { connect } from 'dva'

import { getCityPathsByIdsApi } from '@/api/pcs/cities'
import { deleteCompanionComboApi, enableCompanionComboApi } from '@/api/pcs/pcsCompanionCombo'
import { getHospitalAndAreaNamesByIdsApi, hospitalAndAreaTreeApi } from '@/api/pcs/pcsHospital'
import AekButton from '@/components/AekButton'
import AekLinkButton from '@/components/AekLinkButton'
import AekModal from '@/components/AekModal'
import AekTable from '@/components/AekTable'
import PageLayout from '@/components/PageLayout'
import SearchForm from '@/components/SearchForm'
import { namespace } from '@/models/pcs/pcsCompanionCombo'
import { getPagination, modal, message } from '@/utils/antdHelper'
import { formatMoneyNum } from '@/utils/displayHelper'
import { getBasicFn } from '@/utils/dvaUtil/index'
import { ENABLE_STATUS_ENUM, PCS_COMPANION_CHARGE_MODEL_ENUM, PCS_COMPANION_WAY_ENUM } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

import EditDrawer from './components/EditDrawer'

/** 陪护 - 套餐管理 */
const Index = ({ modelState, loading }) => {
  const { pageList, pagination, searchParams } = modelState
  const { toAction, getLoading } = getBasicFn({ namespace, loading })

  const add = async () => {
    await EditDrawer.PromiseThen()
    message.success('新增成功')
    toAction('getPageList')
  }

  const edit = async row => {
    await EditDrawer.PromiseThen({
      row,
    })
    message.success('修改成功')
    toAction('getPageList')
  }

  const remove = ({ id, name }) => {
    modal.confirm({
      title: '删除',
      content: `确认删除套餐【${name}】？`,
      onOk: async () => {
        await requestWithTry(deleteCompanionComboApi, { id })
        message.success('删除成功')
        if ((pagination.current - 1) * pagination.pageSize === pagination.total - 1) {
          toAction('getPageList', { current: pagination.current - 1 || 1 })
        } else {
          toAction('getPageList')
        }
      },
    })
  }

  const enable = async ({ id }) => {
    await requestWithTry(enableCompanionComboApi, { id, enable: true })
    message.success('启用成功')
    toAction('getPageList')
  }
  const disable = ({ id, name }) => {
    modal.confirm({
      title: '停用',
      content: `确认停用套餐【${name}】？`,
      onOk: async () => {
        await requestWithTry(enableCompanionComboApi, { id, enable: false })
        message.success('停用成功')
        toAction('getPageList')
      },
    })
  }
  /** @type {import("@/components/SearchForm").SearchFormProps} */
  const searchProps = {
    searchParams,
    formData: [
      {
        field: 'name',
        label: '套餐名称',
        component: {
          name: 'Input',
        },
      },
      {
        field: 'areaIdList',
        label: '医院院区',
        component: {
          name: 'AekCascader',
          props: {
            api: hospitalAndAreaTreeApi,
            fieldNames: {
              children: 'areaInfos',
            },
          },
        },
      },
      {
        field: 'enable',
        label: '状态',
        component: {
          name: 'Select',
          props: {
            options: ENABLE_STATUS_ENUM.options,
          },
        },
      },
    ],
    onSearch: values => {
      toAction({ searchParams: values })
      toAction({ pagination: { current: 1 } }, true)
      toAction('getPageList')
    },
  }

  /** @type {import("@/components/AekTable").AekTableProps} */
  const tableProps = {
    configKey: namespace,
    rowKey: 'id',
    loading: getLoading('getPageList'),
    dataSource: pageList,
    pagination: getPagination(pagination, (current, pageSize) => {
      toAction('getPageList', { current, pageSize })
    }),
    columns: [
      { dataIndex: 'name', title: '套餐名称' },
      { dataIndex: 'content', title: '套餐内容', ellipsis: true },
      { dataIndex: 'companionWay', title: '陪护方式', render: text => PCS_COMPANION_WAY_ENUM.getText(text) },
      {
        dataIndex: 'companionType',
        title: '陪护类型',
        width: 150,
        render: (_, { homeServer, homeAreaId, hospitalServer, hospitalAreaId }) =>
          [
            homeServer && (
              <a
                key='homeServer'
                className='mr10px'
                onClick={async () => {
                  const { data } = await requestWithTry(getCityPathsByIdsApi, homeAreaId.split(','))
                  AekModal.PromiseThen({
                    title: '居家服务',
                    showFooter: false,
                    children: (
                      <div>
                        {data.map(name => (
                          <div key={name} className='text-16px'>
                            {name}
                          </div>
                        ))}
                      </div>
                    ),
                  })
                }}
              >
                居家服务
              </a>
            ),
            hospitalServer && (
              <a
                key='hospitalServer'
                onClick={async () => {
                  const { data } = await requestWithTry(getHospitalAndAreaNamesByIdsApi, hospitalAreaId.split(','))
                  AekModal.PromiseThen({
                    title: '住院服务',
                    showFooter: false,
                    children: (
                      <div>
                        {data.map(name => (
                          <div key={name} className='text-16px'>
                            {name}
                          </div>
                        ))}
                      </div>
                    ),
                  })
                }}
              >
                住院服务
              </a>
            ),
          ]
            .filter(Boolean)
            .map(item => item) || '-',
      },
      {
        dataIndex: 'price',
        title: '价格',
        render: (text, { chargeModel }) => (
          <>
            <span className='c-money'>{formatMoneyNum(text)}</span> /{' '}
            {PCS_COMPANION_CHARGE_MODEL_ENUM.getText(chargeModel)}
          </>
        ),
      },
      { dataIndex: 'remark', title: '备注', ellipsis: true },
      {
        dataIndex: 'entranceWeight',
        title: '快捷入口',
        width: 150,
        render: (text, record) =>
          record.quickEntrance ? (
            <span>
              <CheckSquareOutlined className='text-green' />
              {`（权重：${text || ''}）`}
            </span>
          ) : (
            ''
          ),
      },
      { dataIndex: 'enable', title: '状态', enum: ENABLE_STATUS_ENUM },
      {
        key: 'operate',
        title: '操作',
        fixed: 'right',
        width: 150,
        className: 'text-center!',
        render: (_, row) => (
          <>
            <AekLinkButton permissionKey={`${namespace}:update`} onClick={() => edit(row)}>
              编辑
            </AekLinkButton>
            <AekLinkButton permissionKey={`${namespace}:delete`} danger onClick={() => remove(row)}>
              删除
            </AekLinkButton>
            <AekLinkButton
              permissionKey={`${namespace}:enable`}
              danger={row.enable}
              onClick={() => {
                row.enable ? disable(row) : enable(row)
              }}
            >
              {row.enable ? '停用' : '启用'}
            </AekLinkButton>
          </>
        ),
      },
    ],
  }

  return (
    <PageLayout
      extraSuffix={
        <AekButton permissionKey={`${namespace}:create`} type='primary' onClick={add}>
          新建
        </AekButton>
      }
    >
      <SearchForm {...searchProps} />
      <AekTable {...tableProps} />
    </PageLayout>
  )
}

export default connect(store => ({
  modelState: store[namespace],
  loading: store.loading,
}))(Index)
